<template>
  <div class="map-container" :class="{ 'to-right': checkedTool.name && !checkedTool.sleeping }">
    <!-- 地球 -->
    <div id="earth" class="map"></div>
    <div class="overlay" id="nameOverlay"></div>

    <Eye v-if="isFinish && eye" />
    <VcNavigation v-if="isFinish" v-show="nav" :options="options" />
  </div>
</template>

<script>
import { mapMutations, mapState } from "vuex";
import Eye from "../control/eye";
import VcNavigation from "../control/navigation/VcNavigation.vue";
import db from "../../utils/localstorage";
import { isEmptyObject } from "../../utils/tools";
import { changeBasemap } from "../../components/profile/profile";
export default {
  components: { Eye, VcNavigation },
  data() {
    this.handler = null;
    return {
      loading: false,
      value: -90,
      flag: false,
      mapValue: true,
      isFinish: false,
      options: {
        enableCompass: true,
        enableZoomControl: true,
        // enableZoomControl: {
        //   // 缩放比例
        //    zoomAmount: 2,
        //   // 用于在使用重置导航重置地图视图时设置默认视图控制。接受的值是经纬度{lng: number, lat: number, height: number}或者 rectangle{west: number,south: number,east: number,north: number}
        //   defaultResetView: {
        //     lng: 105, lat: 29.999999999999993, height: 19059568.497290563, heading: 360, pitch: -90, roll: 0
        //   },
        //   overrideCamera: false
        // },
        enableDistanceLegend: true,
        enableLocationBar: true,
        // enableLocationBar: {
        //   // 获取更精确的高程
        //   gridFileUrl: 'https://zouyaoji.top/vue-cesium/statics/SampleData/WW15MGH.DAC'
        // },
        enableCompassOuterRing: true,
        enablePrintView: true,
        // enablePrintView: {
        //   // 是否添加 Credit
        //   showCredit: true,
        //   // 是否自动打印
        //   printAutomatically: false
        // },
        // enableMyLocation: false,
        enableMyLocation: {
          // 使用高德api定位
          amap: {
            key: "1337e255f3d26999f4a5ac94dda9022c",
          },
        },
      },
      rm: null
    };
  },
  computed: {
    ...mapState("leftMenu", ["checkedTool"]),
    ...mapState("setting", ["eye", "nav"]),
  },
  mounted() {
    this.loading = true;
    window.earth = new Earth();
    earth
      .create("earth", {
        showFPS: true,
        timeline: false, //底部的时间轴
        baseLayerPicker: false,
        contextOptions: {
          webgl: {
            preserveDrawingBuffer: true
          }
        }
      })
      .then((_viewer) => {
        _viewer._cesiumWidget._creditContainer.style.display = "none"; // 隐藏版权信息
        window.viewer = _viewer;

        // _viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
        //   url: Cesium.IonResource.fromAssetId(1),
        // })

        // 地形
        // viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
        //   url: "http://111.198.39.7:8000/data/global/dem/china12/",
        //   requestVertexNormals: true,
        //   baseLayerPicker: false,
        // });

        //回显设置
        this.initSetting();
        // this.loadArcGIS();
        setTimeout(() => {
          this.isFinish = true;
          // // 罗盘
          // this.initCesiumNavigation();
          this.$emit("onReady");
        }, 1500);

        this.initTileset()

        const helper = new earth.Helper();
        // this.rm = new helper.RightMenu(viewer, 'earth');
        // const menus = [{
        //   text: "编辑",
        //   type: 'menu1',
        //   action: (e) => {
        //     console.log('编辑', e)
        //   }
        // },
        // {
        //   text: "删除",
        //   type: 'menu2',
        //   action: (e) => {
        //     console.log('删除', e)
        //   }
        // }];

        // this.rm.init(menus);

        this.loading = false;
      });
  },
  destroyed() {
    console.log("screen destroyed");
    viewer.dataSources.removeAll();
    window.earth.destroy();
  },
  methods: {
    ...mapMutations("layer", ["addLayerId"]),
    ...mapMutations("setting", ["changeProperty"]),
    initCesiumNavigation() {
      const options = {};
      // 用于在使用重置导航重置地图视图时设置默认视图控制。接受的值是Cesium.Cartographic 和 Cesium.Rectangle.
      options.defaultResetView = Cesium.Rectangle.fromDegrees(80, 22, 130, 50);
      // 用于启用或禁用罗盘。true是启用罗盘，false是禁用罗盘。默认值为true。如果将选项设置为false，则罗盘将不会添加到地图中。
      options.enableCompass = true;
      // 用于启用或禁用缩放控件。true是启用，false是禁用。默认值为true。如果将选项设置为false，则缩放控件将不会添加到地图中。
      options.enableZoomControls = true;
      // 用于启用或禁用距离图例。true是启用，false是禁用。默认值为true。如果将选项设置为false，距离图例将不会添加到地图中。
      options.enableDistanceLegend = true;
      // 用于启用或禁用指南针外环。true是启用，false是禁用。默认值为true。如果将选项设置为false，则该环将可见但无效。
      options.enableCompassOuterRing = true;
      new CesiumNavigation(viewer, options);
    },
    // 回显设置
    initSetting() {
      let setting = db.get("setting");
      if (!isEmptyObject(setting)) {
        Object.keys(setting).map((key) => {
          if (setting[key] != undefined) {
            switch (key) {
              case "fps":
                viewer.scene.debugShowFramesPerSecond = setting[key];
                break;
              case "theme":
                window.document.documentElement.setAttribute(
                  "data-theme",
                  setting[key]
                );
                break;
              case "basemap":
                let map = config.maps.find((e) => e.name == setting[key]) || config.maps[0];
                changeBasemap(map);
                break;
              default:
                break;
            }
            this.changeProperty({ key, value: setting[key] });
          }
        });
      }
    },
    initTileset() {
      console.time('记录耗时')

      const tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
        url: "http://localhost:8088/local/3dtiles/baimo/tileset.json",  //数据路径
        maximumScreenSpaceError: 2,        //最大的屏幕空间误差
        maximumNumberOfLoadedTiles: 1000,  //最大加载瓦片个数
      }));
      viewer.zoomTo(tileset);

      function colorFollowHeight() {
        let hiddenFloors = [2, 3, 4, 5, 6]
        for (let index = 0; index < 1000; index++) {
          hiddenFloors = [2, 3, 4, 5, 6].concat(hiddenFloors);
        }
        // console.log('hiddenFloors: ', hiddenFloors.map(floor => [
        //   `\${floor} === '${floor}'`,           // 替换 'floor' 为实际的 floor 属性名
        //   'color("rgba(255, 0, 0, 0.8)")'       // 隐藏
        // ]).concat([
        //   ['true', 'color("white")']            // 显示其他部分为白色
        // ]));
        let idStyle = new Cesium.Cesium3DTileStyle({
          color: {
            // conditions: [
            //     ['${height}>=100', 'rgba(255, 0, 0, 0.8)'],
            //     ['${height}>=50', 'rgba(0, 255, 0, 0.8)'],
            //     ['${height}>=20', 'rgba(0, 0, 255, 0.8)'],
            //     ['${height}>=0', 'rgba(200, 200, 200, 1)']
            // ]

            conditions: hiddenFloors.map(floor => [
              `\${floor} === '${floor}'`,             // 替换 'id' 为实际的 ID 属性名
              'color("rgba(255, 0, 0, 0.8)")'         // 隐藏
            ]).concat([
              ['true', 'color("white")']              // 显示其他部分为白色
            ])
          },
          // show : '${height}>' + 50
        });
        tileset.style = idStyle;
      }
      tileset.readyPromise.then(function (t) {
        console.log('readyPromise')
        colorFollowHeight();

        console.timeEnd('记录耗时')

        const nameOverlay = $("#nameOverlay");
        let pickedFeatureOld; let oldColor;
        if (Cesium.PostProcessStageLibrary.isSilhouetteSupported(viewer.scene)) {
          viewer.screenSpaceEventHandler.setInputAction(function onMouseMove(movement) {
            const pickedFeature = viewer.scene.pick(movement.endPosition);
            if (!Cesium.defined(pickedFeature)) {
              nameOverlay.hide(0);
              if (pickedFeatureOld && pickedFeatureOld != '') {
                pickedFeatureOld.color = oldColor;
              }
              pickedFeatureOld = '';
              return;
            }
            if (pickedFeatureOld != pickedFeature) {
              if (pickedFeatureOld && pickedFeatureOld != '') {
                pickedFeatureOld.color = oldColor;
              }

              oldColor = pickedFeature.color;
              pickedFeature.color = Cesium.Color.RED;
              pickedFeatureOld = pickedFeature;

              // pickedFeature.color= Cesium.Color.fromRandom({alpha : 0.5})
              const name = pickedFeature.getProperty('name');
              const floor = pickedFeature.getProperty('floor');
              const height = pickedFeature.getProperty('height');

              nameOverlay.html(`<div>名称: <span>${name}</span></div>
                                <div>楼层: <span>${floor}</span></div>
                                <div>高度：<span>${height}</span>米</div>`).show(0).css({
                left: movement.endPosition.x + 20,
                top: movement.endPosition.y + 10
              });
            } else {
              nameOverlay.show(0).css({
                left: movement.endPosition.x + 20,
                top: movement.endPosition.y + 10
              });
            }

          }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        } else {

        }
        //获取点击点坐标
        const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        handler.setInputAction(function (e) {
          const cartesian = viewer.camera.pickEllipsoid(e.position, viewer.scene.globe.ellipsoid);
          const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
          const lon = Cesium.Math.toDegrees(cartographic.longitude).toFixed(5);//四舍五入 小数点后保留五位
          const lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(5);//四舍五入  小数点后保留五位
          // const height = Math.ceil(viewer.camera.positionCartographic.height);   //获取相机高度
          if (cartesian) {
            // console.log(lon + ";" + lat);
          }

          const pickedFeature = viewer.scene.pick(e.position);
          if (Cesium.defined(pickedFeature) && pickedFeature instanceof Cesium.Cesium3DTileFeature) {

            // pickedFeature.setProperty('height', 300);
            setTimeout(() => {
              // colorFollowHeight();
            });
          }

        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.map-container {
  width: 100%;
  height: 100%;
  position: relative;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  background: #000;
  transition: 0.4s;

  &.to-right {
    left: 200px;
  }

  .map-test {
    z-index: 2;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }

  .map-shadow {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 5;
    pointer-events: none;
  }

  .map {
    z-index: 1;
    width: 100%;
    height: 100%;
  }

  .switch-btn {
    z-index: 99;
    padding: 10px;
    position: absolute;
    right: 35px;
    top: 730px;
  }

  .overlay {
    position: fixed;
    z-index: 999;
    font-size: 16px;
    color: #fff;
    pointer-events: none;
    background-color: rgba(0, 0, 0, 0.5);
    width: 200px;
    // height: 150px;
    display: block;
    padding: 10px 15px;
    line-height: 30px;
    display: block;
    top: 0;
    left: 0;
  }

  :deep.el-switch__core {
    border-color: rgb(122, 126, 128) !important;
    background-color: transparent !important;
    box-shadow: 0 0 10px rgb(122, 126, 128);
  }

  :deep.el-switch__core:after {
    background-color: rgb(122, 126, 128) !important;
  }

  :deep.el-switch.is-checked .el-switch__core {
    border-color: rgb(26, 244, 227) !important;
    background-color: transparent !important;
    box-shadow: 0 0 10px rgb(26 244 227);
  }

  :deep.el-switch.is-checked .el-switch__core:after {
    background-color: rgb(26 244 227) !important;
  }

  .block {
    z-index: 99;
    text-align: center;
    position: absolute;
    right: 50px;
    top: 330px;

    span {
      display: inline-block;
      padding: 15px 0;
      color: #04ffed;
    }
  }

  :deep .el-slider__runway {
    background: linear-gradient(0deg, #3a54b3 1%, #04ffed 100%);
    border-radius: 0;
  }

  :deep .el-slider__bar {
    background: transparent;
  }

  :deep .el-slider__button {
    width: 14px;
    height: 14px;
    background: #00e4ff;
    border: none;
  }
}
</style>